import React, { Component } from 'react';

class Index extends Component {
	state = {
		dragEl: null,
		isDrag: false,
		pos: {}
	}
	handleMouseDown = e => {
		const tar = e.target;
		// 判断拖拽元素是否是button
		if (tar.nodeName === 'BUTTON') {
			// 开定位
			tar.style.position = 'absolute'
			// 保存信息
			this.setState({
				dragEl: tar,
				isDrag: true,
				pos: {
					x: e.nativeEvent.offsetX,
					y: e.nativeEvent.offsetY
				}
			})

		}
	}
	handleMouseMove = e => {
		const { isDrag, dragEl, pos } = this.state
		// 是否开启拽拽
		if (isDrag) {
			dragEl.style.left = e.pageX - pos.x + 'px'
			dragEl.style.top = e.pageY - pos.y + 'px'
		}
	}
	handleMouseUp = e => {
		this.setState({
			isDrag: false
		})
	}
	render() {
		const { dragList } = this.props
		return (
			<div>
				<h1>拖住区域</h1>
				<div className="drag" onMouseDown={(e) => this.handleMouseDown(e)}>
					{
						dragList.length > 0 && dragList.map((v, i) => {
							return <button key={i}>{v}</button>
						})
					}
				</div>
			</div>
		);
	}
	componentDidMount() {
		document.addEventListener('mousemove', this.handleMouseMove)
		document.addEventListener('mouseup', this.handleMouseUp)
	}
	componentWillUnmount() {
		document.removeEventListener('mousemove', this.handleMouseMove)
		document.removeEventListener('mouseup', this.handleMouseUp)
	}
}

export default Index;
